#!/usr/bin/env python3
# coding:utf-8

import paho.mqtt.client as mqtt
import struct

# MQTT Broker地址和端口
MQTT_BROKER = 'localhost'
MQTT_PORT = 1883

# 订阅消息的主题
TOPIC = 'test/binary_topic'

# 创建MQTT客户端实例
client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2)

# 定义消息回调函数
def on_message(client, userdata, message):
    # 解析二进制数据
    data = struct.unpack('!I', message.payload)[0]
    print(f"Received binary data: {data} on topic '{message.topic}'")

# 设置消息回调函数
client.on_message = on_message

# 连接到MQTT Broker
client.connect(MQTT_BROKER, MQTT_PORT, 60)

# 订阅消息
client.subscribe(TOPIC)

# 启动网络循环
client.loop_forever()